import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import Details from "../detail.vue";

import {
	getMaterialListApi
} from "@/api/materialApi";
import {
	createWarehouseCheckApi,
	getWarehouseCheckListApi,
	updateWarehouseCheckApi,
	delWarehouseCheckApi,
	getWarehouseCheckShowApi
} from "@/api/warehouseApi";
export function usePage() {
  const form = reactive({
    page: 1,
    perPage: 10,
    checkNo: null
  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const getOrderType = (type) => {
    switch (type) {
      case 1:
        return "物料盘点";
      case 2:
        return "仓库盘点";
    }
  };

  const getTotalNum = (num, text = false) => {
    
	if(num === 0) {
		return text ? num : "info";
	}else if(num > 0) {
		return text ? num : "success";
	}else{
		return text ? num : "danger";
	}
  };
  const columns: TableColumnList = [
    {
      label: "ID",
      prop: "warehouseCheckId",
      width: 80
    },
	{
	  label: "盘点单号",
	  prop: "checkNo",
	  minWidth: 130
	},
	{
	  label: "盈亏数",
	  prop: "totalNum",
	  cellRenderer: ({ row }) => (
	    <el-tag size="large" type={getTotalNum(row.totalNum)} effect="light">
	      {getTotalNum(row.totalNum, true)}
	    </el-tag>
	  ),
	  minWidth: 100
	},
	{
	  label: "所属仓库",
	  prop: "warehouseLocation.name",
	  formatter: (row: any) => {
		if(row.checkType === 1) {
			return ''
		}
	  	return row.warehouse?.name+'/'+row.warehouseArea?.name+'/'+row.warehouseLocation?.name
	  },
	  minWidth: 200
	},
    {
      label: "盘点类型",
      prop: "checkType",
      minWidth: 130,
	  formatter: (row) => {
	  	return getOrderType(row.checkType)
	  }
    },
	{
	  label: "盘点状态",
	  prop: "status",
	  minWidth: 130,
	  cellRenderer: ({ row }) => (
	    <span style={row.status === 1?'color:#e6a23c':'color:#67c23a'}>
	      {row.status===1?'盘库中':'已完成'}
	    </span>
	  ),
	},
    {
    	label: "创建者",
    	prop: "createUser.username",
    	minWidth: 100
    },
    {
    	label: "创建时间",
    	prop: "createdAt",
    	minWidth: 160
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
	  width: 180
    }
  ];
  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    getWarehouseCheckListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.perPage*1;
      pagination.currentPage = 1;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
	console.log(val)
    getWarehouseCheckListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
	  pagination.pageSize = result.result.perPage*1;
	  pagination.currentPage = val;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  async function onSearch() {
    loading.value = true;
    const { result } = await getWarehouseCheckListApi(toRaw(form));
    dataList.value = result.list;
    pagination.total = result.total;
    pagination.pageSize = result.perPage*1;
    pagination.currentPage = result.page*1;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }
  const materialOptions = ref()
  const getMaterialData = async() => {
  	const res = await getMaterialListApi({page:1, perPage: 9999})
  	if(res?.code === 200) {
  		materialOptions.value = res.result.list
  	}
  }
  const resetForm = formEl => {
    if (!formEl) return;
    form.checkNo = null;
    formEl.resetFields();
    onSearch();
  };
  const formInline = ref();
  async function openDialog(title = "新增", row?: FormItemProps) {
	
    if (`${title}` == "新增") {
      formInline.value = {
        title: "新增",
		checkNo: 'RE'+(new Date()).toLocaleString().replace(/[:/ ]/g, ''),
		totalNum: 0,
		checkType: 1,
		materialOptions: materialOptions.value
      };
    } else {
      const res = await getWarehouseCheckShowApi({
        warehouseCheckId: row?.warehouseCheckId
      });
	  if(res.code !== 200) {
	  	message(res.msg ?? "操作失败,请联系管理员", {
	  	  type: "error"
	  	});
	  	return
	  }
      formInline.value = {
        title: "修改",
		materialOptions: materialOptions.value,
        warehouseCheckId: row?.warehouseCheckId ?? null,
		checkNo: res?.result?.checkNo ?? null,
		checkType: res?.result?.checkType ?? null,
		materialList: res?.result?.orderProducts ?? [],
		productList: res?.result?.checkProducts ?? [],
		supplierId: res?.result?.supplierId ?? null,
		totalNum: res?.result?.totalNum ?? 0,
		status: res?.result?.status ?? 1,
		materialId: res?.result?.checkProducts[0].materialId ?? []
      };
    }
    addDialog({
      title: `${title}库存盘点信息`,
      props: {
        formInline: formInline
      },
      width: "75%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
	  // hideFooter: true,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了库存盘点`, {
            type: "success"
          });
          done();
          onSearch();
        }
		function hasDuplicateField(array, field) {
		  const uniqueValues = new Set();
		  for (const obj of array) {
		    if (uniqueValues.has(obj[field])) {
		      return true;
		    }
		    uniqueValues.add(obj[field]);
		  }
		  return false;
		}
        FormRef.validate(valid => {
          if (valid) {
			  
			if(curData.productList.length <= 0) {
				message("请选择物料", {
				  type: "error"
				});
				return
			}
			if(hasDuplicateField(curData.productList, 'materialId')) {
				message("重复物料", {
				  type: "error"
				});
				return
			}
			let params = {
				checkNo: curData.checkNo,
				totalNum: curData.totalNum,
				checkType: curData.checkType,
				warehouseId: curData.warehouseId,
				warehouseAreaId: curData.warehouseAreaId,
				warehouseLocationId: curData.warehouseLocationId,
				status: curData.status,
				productList: curData.productList,
				warehouseCheckId: curData.warehouseCheckId,
			}
			
            if (title === "新增") {
              createWarehouseCheckApi(params)
                .then((res) => {
				  if(res.code !== 200) {
				  	message(res.msg ?? "操作失败,请联系管理员", {
				  	  type: "error"
				  	});
				  	return
				  }
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            } else {
              updateWarehouseCheckApi(params)
                .then((res) => {
				  if(res.code !== 200) {
				  	message(res.msg ?? "操作失败,请联系管理员", {
				  	  type: "error"
				  	});
				  	return
				  }
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            }
          }
        });
      }
    });
  }
  onMounted(async () => {
    onSearch();
	getMaterialData();
  });

  function handleDelete(row) {
    delWarehouseCheckApi({ warehouseCheckId: row.warehouseCheckId }).then((res) => {
	  if(res.code !== 200) {
	  	message(res.msg ?? "操作失败,请联系管理员", {
	  	  type: "error"
	  	});
	  	return
	  }
      message(`删除成功`, { type: "success" });
      onSearch();
    });
  }
  function onDetail(row) {
	getWarehouseCheckShowApi({ warehouseCheckId: row.warehouseCheckId }).then(res => {
		if(res?.code === 200) {
			// for (let item of materialOptions.value) {
			// 	for (let row of res.result.orderProducts) {
					
			// 		if(item.materialId === row.materialId) {
			// 			row.materialCode = item.code
			// 			row.materialName = item.name
			// 			row.categoryName = item.category.name
			// 			row.unitName = item.unit.name
			// 			row.actualityNum = 0
						
			// 		}
			// 	}
			// }
			res.result.orderTypeName = getOrderType(res.result.orderType)
			addDialog({
				top: "5vh",
				width: "70%",
				title: "库存盘点详情",
				hideFooter: true,
				contentRenderer: () => h(Details),
				props: {
					info: res.result
				}
			});
		}
		
	});
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete,
	onDetail,
  };
}
